<template>
  <div class="material-edit">
    <a-form :form="form" :label-col="{ span: 6, sm: 8, lg: 6 }" :wrapper-col="{ span: 7, sm: 12, lg: 7 }" @submit="handleSubmit">
      <a-form-item label="素材名称">
        <a-input placeholder="4-20个字" v-decorator="['materialName', { rules: [{ required: true, message: '必须填写素材名称' }] }]" />
      </a-form-item>
      <a-form-item label="素材类型">
        <a-select v-decorator="['advertType', { initialValue: 0 }]">
          <a-select-option :value="0">
            互动广告素材
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="素材子类型">
        <a-select @change="handleSelectChange" v-decorator="['materialType', { initialValue: 0 }]">
          <a-select-option v-for="items in materialChildType" :value="items.v" :key="items.v">
            {{ items.value }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <!--  v-decorator="['bannerImg', { rules: { required: true, message: '请选择上传文件' } }]" -->
      <a-form-item :label="currentTitle">
        <template v-if="!specialUpload">
          <a-upload
            v-decorator="[
              'bannerImg',
              {
                valuePropName: 'fileList',
                getValueFromEvent: normFile,
                rules: [{ required: true, message: '请选择上传文件' }],
              },
            ]"
            name="file"
            list-type="picture-card"
            class="avatar-uploader"
            :show-upload-list="false"
            :action="uploadImgAPI"
            :before-upload="beforeUpload"
            @change="(info) => handleChange(info, 'bannerUrl', 'bannerImgLoading')"
            :headers="{
              token,
            }"
            :data="{
              filePath: 'images/',
            }"
          >
            <img v-if="bannerUrl" style="width:100%;" :src="bannerUrl" alt="avatar" />
            <div v-else>
              <a-icon :type="bannerImgLoading ? 'loading' : 'plus'" />
              <div class="ant-upload-text">
                Upload
              </div>
            </div>
          </a-upload>
        </template>
        <!-- end 1 -->
        <template v-if="specialUpload">
          <div class="box">
            <a-upload
              name="file"
              v-decorator="[
                'top',
                {
                  valuePropName: 'top',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '上部图片不能为空' }],
                },
              ]"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgAPI"
              :before-upload="beforeUpload"
              @change="(info) => handleChange(info, 'topUrl', 'topUrlLoading')"
              :headers="{
                token,
              }"
              :data="{
                filePath: 'images/',
              }"
            >
              <img v-if="topUrl" style="width:100%;" :src="topUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="topUrlLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <span>上部 750*440</span>
          </div>
          <div class="box">
            <a-upload
              name="file"
              v-decorator="[
                'close',
                {
                  valuePropName: 'close',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '未打开图片不能为空' }],
                },
              ]"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgAPI"
              :before-upload="beforeUpload"
              @change="(info) => handleChange(info, 'closeUrl', 'closeUrlLoading')"
              :headers="{
                token,
              }"
              :data="{
                filePath: 'images/',
              }"
            >
              <img v-if="closeUrl" style="width:100%;" :src="closeUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="closeUrlLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <span>未打开 230*290</span>
          </div>
          <div class="box">
            <a-upload
              name="file"
              v-decorator="[
                'prize',
                {
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '中奖图片不能为空' }],
                },
              ]"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgAPI"
              :before-upload="beforeUpload"
              @change="(info) => handleChange(info, 'prizeUrl', 'prizeUrlLoading')"
              :headers="{
                token,
              }"
              :data="{
                filePath: 'images/',
              }"
            >
              <img v-if="prizeUrl" style="width:100%;" :src="prizeUrl" alt="avatar" />
              <div v-else>
                <a-icon :type="prizeUrlLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <span>已打开 230*290</span>
          </div>
          <div class="box">
            <a-upload
              name="file"
              v-decorator="[
                'noPrize1',
                {
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '未中奖1图片不能为空' }],
                },
              ]"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgAPI"
              :before-upload="beforeUpload"
              @change="(info) => handleChange(info, 'noPrize1Url', 'noPrize1UrlLoading')"
              :headers="{
                token,
              }"
              :data="{
                filePath: 'images/',
              }"
            >
              <img v-if="noPrize1Url" style="width:100%;" :src="noPrize1Url" alt="avatar" />
              <div v-else>
                <a-icon :type="noPrize1UrlLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <span>未中奖1 230*290</span>
          </div>
          <div class="box">
            <a-upload
              name="file"
              v-decorator="[
                'noPrize2',
                {
                  valuePropName: 'fileList',
                  getValueFromEvent: normFile,
                  rules: [{ required: true, message: '未中奖2图片不能为空' }],
                },
              ]"
              list-type="picture-card"
              class="avatar-uploader"
              :show-upload-list="false"
              :action="uploadImgAPI"
              :before-upload="beforeUpload"
              @change="(info) => handleChange(info, 'noPrize2Url', 'noPrize2UrlLoading')"
              :headers="{
                token,
              }"
              :data="{
                filePath: 'images/',
              }"
            >
              <img v-if="noPrize2Url" style="width:100%;" :src="noPrize2Url" alt="avatar" />
              <div v-else>
                <a-icon :type="noPrize2UrlLoading ? 'loading' : 'plus'" />
                <div class="ant-upload-text">
                  Upload
                </div>
              </div>
            </a-upload>
            <span>未中奖2 230*290</span>
          </div>
        </template>
      </a-form-item>
      <a-form-item label="奖品标题">
        <a-input placeholder="4-20个字" v-decorator="['awardTitle', { rules: [{ required: true, message: '必须填写奖品标题' }] }]" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 12, offset: 6 }">
        <a-space>
          <a-button type="primary" html-type="submit">
            保存
          </a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>

<script>
const token = localStorage.getItem('Authorization')
import { postMaterialUpdate } from '@/api/Advertising/api'
import { uploadImgAPI } from '@/api/baseUrl'
import { toRoute } from '@/lib/utils'
export default {
  name: 'MaterialEdit',
  data() {
    return {
      token,
      uploadImgAPI,
      formLayout: 'horizontal',
      //status
      bannerImgLoading: false,
      closeUrlLoading: false,
      topUrlLoading: false,
      prizeUrlLoading: false,
      noPrize1UrlLoading: false,
      noPrize2UrlLoading: false,
      bannerUrl: '',
      closeUrl: '',
      topUrl: '',
      prizeUrl: '',
      noPrize1Url: '',
      noPrize2Url: '',
      //status end
      currentTitle: '普通弹层 640*300',
      specialUpload: false,
      form: this.$form.createForm(this, { name: 'myForm' }),
      materialChildType: [
        { v: 0, value: '普通弹层', s: '640*300', k: 'hd0' },
        { v: 1, value: '刮刮卡弹层', s: '678*810', k: 'hd1' },
        { v: 2, value: '三选一弹层', s: '', k: 'hd2' },
        { v: 3, value: '自定义弹层', s: '750*600~800', k: 'hd3' },
      ],
    }
  },
  methods: {
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, fieldsValue) => {
        console.log(fieldsValue)
        if (!err) {
          if (!this.specialUpload) {
            const values = {
              ...fieldsValue,
              awardIconImg: '',
              buttonText: '立即领取',
              images: {},
              bannerImg: fieldsValue?.bannerImg[0]?.response?.data ?? '-',
            }
            console.log(values)
            this.materialUpdate(values ?? {})
          } else {
            const values = {
              ...fieldsValue,
              awardIconImg: '',
              buttonText: '立即领取',
              images: {
                close: fieldsValue?.close[0]?.response?.data ?? '-',
                top: fieldsValue?.top[0]?.response?.data ?? '-',
                noPrize1: fieldsValue?.noPrize1[0]?.response?.data ?? '-',
                noPrize2: fieldsValue?.noPrize2[0]?.response?.data ?? '-',
                prize: fieldsValue?.prize[0]?.response?.data ?? '-',
              },
              bannerImg: '-',
            }
            console.log(values)
            this.materialUpdate(values ?? {})
          }
        }
      })
    },
    /**
     * @func 文件校验
     */
    normFile(e) {
      console.log('Upload event:', e)
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList
    },
    /**
     * @func 新建素材
     */
    async materialUpdate(param) {
      const [err, data] = await postMaterialUpdate(param)
      if (!err) {
        this.$msgSuc('提交成功!')
        toRoute(this, 'material')
      } else {
        this.$msgErr(err)
      }
    },
    /**
     * @func 素材子类型切换
     */
    handleSelectChange(current) {
      const { value, s } = this.materialChildType[current]
      /**
       * @desc 设置当前title
       */
      const currentTitle = `${value} ${s}`
      this.currentTitle = currentTitle
      /**
       * @desc 当前弹框为三选一类型
       */
      /**
       * @desc 设置上传显示数量
       */
      current == 2 ? (this.specialUpload = true) : (this.specialUpload = false)
    },
    /**
     * @func 获取Base64
     */
    getBase64(img, callback) {
      const reader = new FileReader()
      reader.addEventListener('load', () => callback(reader.result))
      reader.readAsDataURL(img)
    },
    /**
     * @func 上传时状态控制
     */
    handleChange(info, url, loading) {
      const SUCCESS_STATUS = '000000'
      if (info.file.status === 'uploading') {
        this[loading] = true
        return
      }
      if (info.file.status === 'done') {
        this.getBase64(info.file.originFileObj, (imageUrl) => {
          if (info.file.response.code == SUCCESS_STATUS) {
            this[url] = imageUrl
            this[loading] = false
          } else {
            this.$msgErr('上传失败!')
          }
        })
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'image/gif'
      if (!isJpgOrPng) {
        this.$msgErr('只能上传图片形式的文件！')
      }
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$msgErr('图片应该小于2MB!')
      }

      return isJpgOrPng && isLt2M
    },
  },
}
</script>
<style lang="scss" scoped>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
.box {
  display: inline-flex;
  flex-direction: column;
  width: 33.33%;
}
</style>
